package net.zigin.nhi.waste.view.widget;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gyf.immersionbar.ImmersionBar;

import net.zigin.nhi.waste.R;
import net.zigin.nhi.waste.adapter.IDialogUpData;
import net.zigin.nhi.waste.adapter.NoDataAdapter;
import net.zigin.nhi.waste.adapter.OfficeChildrenAdapter;
import net.zigin.nhi.waste.adapter.OfficeParentAdapter;
import net.zigin.nhi.waste.bean.DepartBean;
import net.zigin.nhi.waste.constants.Constants;
import net.zigin.nhi.waste.net.ApiCall;
import net.zigin.nhi.waste.net.BaseResponse;
import net.zigin.nhi.waste.net.HttpRetrofitClient;
import net.zigin.nhi.waste.net.PublicService;
import net.zigin.nhi.waste.utils.StringUtil;

import java.util.ArrayList;
import java.util.List;

import io.paperdb.Paper;
import io.reactivex.Observable;

public class OfficeDialog extends Dialog {

    private View mViewNone;
    private Button mClose;
    private RecyclerView mRvParent;
    private RecyclerView mRvChildren;
    private Button mConfirm;
    private Activity activity;
    private IDialogUpData dd;
    public static OfficeDialog mInstance;

    private int count = 0;  //计数getDepartName()方法重复执行了几次
    private List<String> parentList = new ArrayList<>();
    private List<String> nameList = new ArrayList<>();
    private List<String> idList = new ArrayList<>();
    private String departName = "";
    private String parentId = "";
    private List<String> parentIdList = new ArrayList<>();

    public OfficeDialog(@NonNull Context context, Activity activity, IDialogUpData dd) {
        super(context);
        this.activity = activity;
        this.dd = dd;
    }

    //单例保证每次弹出的dialog唯一
    public static OfficeDialog getInstance(Context context, Activity activity, IDialogUpData dd) {
        if (mInstance == null) {
            synchronized (OfficeDialog.class) {
                if (mInstance == null) {
                    mInstance = new OfficeDialog(context, activity, dd);
                }
            }
        }
        return mInstance;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_office);
        initView();
        initData();
    }

    private void initView() {
        ImmersionBar.with(activity, this).init();
        mViewNone = findViewById(R.id.view_none);
        mClose = findViewById(R.id.close);
        mRvParent = findViewById(R.id.rv_parent);
        mRvChildren = findViewById(R.id.rv_children);
        mConfirm = findViewById(R.id.confirm);

        Window window = this.getWindow();
        window.setBackgroundDrawable(null);
        // 设置宽高
        window.setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        // 设置弹出的动画效果
        window.setWindowAnimations(R.style.AnimBottom);
        mViewNone = window.findViewById(R.id.view_none);
        mViewNone.getBackground().setAlpha(0);

        LinearLayoutManager manager = new LinearLayoutManager(activity);
        manager.setOrientation(RecyclerView.HORIZONTAL);
        mRvParent.setLayoutManager(manager);
        mRvChildren.setLayoutManager(new LinearLayoutManager(activity));
    }


    private void initData() {
        mViewNone.setOnClickListener(v -> {
            dismiss();
            ImmersionBar.destroy(activity, this);
        });

        mClose.setOnClickListener(v -> {
            dismiss();
            ImmersionBar.destroy(activity, this);
        });

        getDepartName();

        mConfirm.setOnClickListener(v -> {
            if (StringUtil.isNotEmpty(departName)) {
                dd.upDataUi(departName, parentId);
            }
            dismiss();
        });
    }

    /**
     * 获取科室列表
     */
    private void getDepartName() {
        Observable<BaseResponse<String>> observable = HttpRetrofitClient.getInstance().create(PublicService.class)
                .getDepartByHospitalBaseId(Paper.book().read(Constants.TOKEN), parentId);
        HttpRetrofitClient.execute(observable, new ApiCall<String>() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            protected void success(String data) {
                if (StringUtil.isNotEmpty(data)) {
                    Log.i("科室列表", data);
                    List<DepartBean> beanList = JSONArray.parseArray(data, DepartBean.class);
                    if (beanList != null && beanList.size() > 0) {
                        nameList.clear();
                        idList.clear();
                        for (DepartBean departBean : beanList) {
                            nameList.add(departBean.getName());
                            idList.add(departBean.getId());
                        }

                        parentList.add("请选择");
                        OfficeParentAdapter parentAdapter = new OfficeParentAdapter(parentList);
                        mRvParent.setAdapter(parentAdapter);
                        parentAdapter.setPosition(count);
                        parentAdapter.setGetListener((position, text) -> {
                            parentAdapter.setPosition(position);
                            parentAdapter.notifyDataSetChanged();
                            if (position == 0) {
                                parentId = "";
                                parentIdList.clear();
                            } else {
                                parentId = parentIdList.get(position - 1);
                            }

                            List<String> newList = new ArrayList<>();
                            for (int i = 0; i < parentList.size(); i++) {
                                if (i >= position) {
                                    newList.add(parentList.get(i));
                                    count = position;
                                }
                            }
                            parentList.removeAll(newList);
                            getDepartName();
                        });

                        if (nameList.size() > 0) {
                            OfficeChildrenAdapter childrenAdapter = new OfficeChildrenAdapter(nameList);
                            mRvChildren.setAdapter(childrenAdapter);
                            childrenAdapter.setGetListener((position, text) -> {
                                childrenAdapter.setPosition(position);
                                childrenAdapter.notifyDataSetChanged();

                                departName = nameList.get(position);
                                //将第一层赋值成选中的
                                if (nameList.contains(parentList.get(count)) || parentList.get(count).equals("请选择")) {
                                    parentList.remove(count);
                                }
                                parentList.add(departName);
                                parentAdapter.notifyDataSetChanged();

                                parentId = idList.get(position);
                                parentIdList.add(parentId);
                                getDepartName();
                                count++;
                            });
                        }
                    } else {
                        count = 0;
                    }
                }
            }
        });
    }
}
